package com.fancy.mobileschool.ui;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;


import com.fancy.mobileschool.MyConfiguration;
import com.fancy.mobileschool.R;
import com.fancy.mobileschool.entity.Course;
import com.fancy.mobileschool.entity.YunFile;
import com.fancy.mobileschool.service.YunFileService;
import com.fancy.mobileschool.task.TaskExecutor;
import com.fancy.mobileschool.ui.fragment.CourseShareFileFragment;
import com.fancy.mobileschool.ui.fragment.MyYunFileFragment;
import com.fancy.mobileschool.ui.fragment.TransferFileListFragment;
import com.fancy.mobileschool.ui.widget.CourseSelectDialog;

import java.io.File;
import java.util.List;

public class YunFileActivity extends AppCompatActivity implements MyYunFileFragment.GetMyFile, CourseSelectDialog.CourseSelectedListener{

    private final static int GET_My_FILES = 1;

    private final static int GET_MY_SHARECOURSE = 2;

    private final static int UPLOAD_PERSON_FILE_RESULT = 3;

    private final static int UPLOAD_COURSE_FILE_RESULT = 6;

    private final static int UPLOAD_PERSON_FILE = 4;

    private final static int UPLOAD_COURSE_FILE = 5;

    private MyYunFileFragment myYunFileFragment;

    private CourseShareFileFragment courseShareFileFragment;

    private TransferFileListFragment transferFileListFragment;

    private File resultFile;

    private FloatingActionButton fab;

    private YunFileService yunFileService;

    private volatile int currentPage = 0;

    private List<Course> courses;

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yun_file_pager);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        myYunFileFragment = new MyYunFileFragment();
        transferFileListFragment = new TransferFileListFragment();
        yunFileService = new YunFileService();
        if (mSectionsPagerAdapter.getCount() == 3)
            courseShareFileFragment = new CourseShareFileFragment();

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(YunFileActivity.this, UploadFileActivity.class);
                startActivityForResult(i, 1);
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_yun_file_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String filePath = data.getStringExtra("file");
        if (filePath != null && ! "".equals(filePath)) {
            resultFile = new File(filePath);
            if (currentPage == 0) {
                uploadFile(resultFile);
            }else if (currentPage == 2) {
                if (courses != null) {
                    CourseSelectDialog dialog = new CourseSelectDialog(this, courses, this, true);
                    dialog.show();
                }else
                    Toast.makeText(getApplicationContext(), "请先建立课程公共目录", Toast.LENGTH_SHORT).show();
            }
            //uploadFile(file);
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == GET_My_FILES) {
                List<YunFile> files = (List<YunFile>) msg.obj;
                myYunFileFragment.UpdateFilesList(files);
            }else if (msg.what == GET_MY_SHARECOURSE) {
                List<Course> tempCourses = (List<Course>) msg.obj;
                courseShareFileFragment.setAdapter(tempCourses);
                YunFileActivity.this.courses = tempCourses;
            }else if (msg.what == UPLOAD_PERSON_FILE_RESULT || msg.what == UPLOAD_COURSE_FILE_RESULT) {
                int result = msg.arg1;
                YunFile yunFile = (YunFile) msg.obj;
                transferFileListFragment.moveUploadFile2End(yunFile);
                showResult(result);
            }else if (msg.what == UPLOAD_PERSON_FILE || msg.what == UPLOAD_COURSE_FILE) {
                transferFileListFragment.addFile2Upload((YunFile) msg.obj);
            }
        }

        private void showResult(int result) {
            if (result > 0)
                Toast.makeText(getApplicationContext(), "上传成功", Toast.LENGTH_SHORT).show();
            else
                Toast.makeText(getApplicationContext(), "上传失败", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void getMyYunFiles() {
        TaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                List<YunFile> files = yunFileService.getMyYunFiles(MyConfiguration.myID);
                Message message = handler.obtainMessage();
                message.obj = files;
                message.what = GET_My_FILES;
                handler.sendMessage(message);
            }
        });
    }

    public void getShareCourse() {
        TaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                List<Course> courses = yunFileService.getShareCourse();
                Message message = handler.obtainMessage();
                message.obj = courses;
                message.what = GET_MY_SHARECOURSE;
                handler.sendMessage(message);
            }
        });
    }

    public void uploadFile(final File file) {
        TaskExecutor.execute(new Runnable() {
            @Override
            public void run() {

                YunFile yunFile = new YunFile(0, file.getName(), "", "", "personFile");
                Message message = handler.obtainMessage();
                message.obj = yunFile;
                message.what = UPLOAD_PERSON_FILE;
                handler.sendMessage(message);


                boolean result = yunFileService.uploadPersonFile(file, MyConfiguration.myID);
                Message message1 = handler.obtainMessage();
                message1.obj = yunFile;
                message1.what = UPLOAD_PERSON_FILE_RESULT;
                if (result) message1.arg1 = 1;
                else message1.arg1 = -1;
                handler.sendMessage(message1);
            }
        });
    }

    @Override
    public void courseSelect(final String courseName) {
        TaskExecutor.execute(new Runnable() {
            @Override
            public void run() {

                YunFile yunFile = new YunFile(0, resultFile.getName(), "", "", "courseFile");
                Message message = handler.obtainMessage();
                message.obj = yunFile;
                message.what = UPLOAD_COURSE_FILE;
                handler.sendMessage(message);


                boolean result = yunFileService.uploadCourseFile(resultFile, courseName, MyConfiguration.myID);
                Message msg = handler.obtainMessage();
                if (result) msg.arg1 = 1;
                else msg.arg1 = -1;
                msg.what = UPLOAD_COURSE_FILE_RESULT;
                msg.obj = new YunFile(0, resultFile.getName(), "", "", "courseFile");
                handler.sendMessage(msg);
            }
        });
    }


    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            if (position == 0)
                return myYunFileFragment;
            else if (position == 1)
                return transferFileListFragment;
            else
                return courseShareFileFragment;
        }


        @Override
        public int getCount() {
            // Show 3 total pages.
            if (MyConfiguration.type.equals("student"))
                return 2;
            else
                return 3;
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            currentPage = position;
            if (currentPage == 0 || currentPage == 2)
                fab.show();
            else
                fab.hide();
            super.setPrimaryItem(container, position, object);
        }


        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "私人云端文件";
                case 1:
                    return "传输列表";
                case 2:
                    return "课程公有文件";
            }
            return null;
        }
    }
}
